<?php 
	require_once("init.php"); 
?>

<?php
	$errorMessage = ""; 
	$success = false;
	if (isset($_POST["question"]) && isset($_POST["answer1"]) && isset($_POST["answer2"])) {
		if (strlen($_POST["question"]) == 0 || strlen($_POST["answer1"]) == 0 || strlen($_POST["answer2"]) == 0) {
			$errorMessage = "Please enter the question and answers.";
		} else {
			// Check if user exists
			$qCheckTopic = mysql_query("
				SELECT *
				FROM topics
				WHERE question = '".$_POST["question"]."'
					AND answer1 = '".$_POST["answer1"]."'
					AND answer2 = '".$_POST["answer2"]."'
			");
			if (mysql_num_rows($qCheckTopic) > 0) {
				$errorMessage = "This topic has been posted in the past:";
			} else {
				// Register new user account
				$qInsertTopic = mysql_query("
					INSERT INTO topics (
						userId,
						question,
						answer1,
						answer2,
						categoryId,
						dateAdded,
						dateClosed
					)
					VALUES (
						".$_SESSION["userId"].",
						'".$_POST["question"]."',
						'".$_POST["answer1"]."',
						'".$_POST["answer2"]."',
						".$_POST["categoryId"].",
						now(),
						date_add(now(), interval 28 day)
					)
				");
						
				// Update user points
				if (isset($_SESSION["userId"])) {
					$qUpdateUserPoints = mysql_query("
						UPDATE users
						SET 
							points = points + ".$submitTopicPoints."
						WHERE 
							userId = ".$_SESSION["userId"]."
					");
				}
				
				$success = true;
?>
<form id="submitTopicSuccess" class="dialog" method="post" target="_self" action="redirect.php?url=index.php">
	<fieldset>
    <h1>Thank you!</h1>
    <p align="center">Your topic has been successfully posted.</p>
    <p align="center"><input class="submit" type="submit" name="submit" value="Continue" /></p>
  </fieldset>
</form>
<?php
			}
		}
	}
	
	if (!$success) {
		// New topics
		$qCategories = mysql_query("
			SELECT * 
			FROM categories
		");
?>  
<form id="submitTopicForm" class="dialog" method="post" action="submittopic.php">
  <fieldset>
    <h1>Post New Topic</h1>
    <a class="button leftButton" type="cancel">Cancel</a>
    <label>Question:</label>
    <input type="text" name="question" maxlength="25" />
    <label>Answer 1:</label>
    <input type="text" name="answer1" maxlength="15" />
    <label>Answer 2:</label>
    <input type="text" name="answer2" maxlength="15" />
    <label>Category:</label>
    <select name="categoryId">
  		<?php 
				while ($row = mysql_fetch_array($qCategories)) { 
			?>
      <option value="<?php print $row["categoryId"]; ?>">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php print $row["name"]; ?></option>
      <?php
				}
			?>
    </select>
    <p class="error" align="center"><?php print $errorMessage; ?></p>
	  <p align="center"><input class="submit" type="submit" name="submit" value="Post topic" /></p>
  </fieldset>
</form>
<?php
	}
?>